package com.ahui.server.service.impl;

import com.ahui.server.config.serurity.JwTokenUtil;
import com.ahui.server.pojo.Admin;
import com.ahui.server.mapper.AdminMapper;
import com.ahui.server.pojo.RespBean;
import com.ahui.server.service.IAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static jdk.nashorn.internal.objects.NativeMath.log;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ahui
 * @since 2021-04-21
 */
@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    /**
     * SpringSecurity提供的一个加密密码的工具
     */
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwTokenUtil jwTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    /**
     * 登录之后返回token
     *
     * @param username
     * @param password
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password, HttpServletRequest request) {
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        //判断是否为空或者用户名密码不正确  数据库会加密，所以用matches匹配
        log.info("哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈");
        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确");
        }

        //判断userDetails是否被禁用
        if (!userDetails.isEnabled()) {
            return RespBean.error("用户被禁用，请联系管理员");
        }
        //更新Security登录用户对象,且放入Security的全文中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //判断成功，根据工具类JwTokenUtil拿到令牌
        String token = jwTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHeader);
        return RespBean.success("登录成功", tokenMap);
    }


    /**
     * 根据用户获取对象
     *
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        //使用的mybatis-plus所以调用相应的指定方法
        //判断username字段是否匹配，并且用户是否被禁用（是否启用），即enabled字段是否为false
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username)
                .eq("enabled", true));
    }
}
